#!/usr/bin/python3
# -*- coding: utf-8 -*-

import time
from typing import Literal

import allure
from playwright.sync_api import Page

from models.base_page import BasePage
from models.network_page.eip_page.eip_details_page import EIPDetailPage
from utils.log import log


class EIPPage(BasePage):
    def __init__(self, page: Page):
        super().__init__(page)
        self.route = "eips"
        self.route1 = "eip_v4"
        self.route2 = "eip_v6"
        self.details_page = EIPDetailPage(page)

    @allure.step("点击创建EIP按钮")
    def click_allocate_eip_button(self):
        """点击创建EIP按钮"""
        self.toolbar.click_allocate_button()

    @allure.step("输入EIP名称")
    def input_eip_name(self, eip_name: str) -> None:
        """输入EIP名称"""
        self.locator("input[name=\"eip_name\"]").fill(eip_name)

    @allure.step("选择计费模式")
    def select_bandwidth_mode(self, bandwidth: Literal["bandwidth", "traffic"] = 'bandwidth'):
        """
        选择计费模式
        :param bandwidth: 可选按带宽： bandwidth 和 按流量：traffic
        :return:
        """
        if bandwidth == 'bandwidth':
            self.select.select_option(select_option="select[name=\"billing_mode\"]", value='bandwidth')
        elif bandwidth == 'traffic':
            self.select.select_option(select_option="select[name=\"billing_mode\"]", value='traffic')

    @allure.step("输入带宽上限")
    def input_bandwidth_upper_limit(self, bandwidth_upper_limit=1):
        """输入带宽上限"""
        locator = self.locator("input[name=\"bandwidth\"]")
        locator.click()
        locator.fill(str(bandwidth_upper_limit))
        locator.press("Enter")

    @allure.step("选择IP组")
    def select_ip_group(self, name="选择 IP 组"):
        """选择IP组"""
        self.page.get_by_role(role="link", name=name).click()

    @allure.step("选择绑定方式")
    def select_associate_mode(self, associate_mode: Literal[
        "internal_binding", "external_binding"] = 'external_binding') -> None:
        """选择绑定方式，默认外部绑定"""
        if associate_mode == 'external_binding':
            self.page.get_by_label("外部绑定").check()
        elif associate_mode == 'internal_binding':
            self.page.get_by_label("内部绑定 (?)").check()

    @allure.step("选择是否备案")
    def select_need_icp(self, icp: Literal["not_need_icp", "need_icp"] = "not_need_icp") -> None:
        """选择是否备案"""
        if icp == "not_need_icp":
            self.page.get_by_label("不需要 (?)").check()
        elif icp == "need_icp":
            self.page.get_by_label("需要 (?)", exact=True).check()

    @allure.step("输入创建数量")
    def input_count(self, num=1):
        """输入创建数量"""
        self.locator("input[name=\"count\"]").fill(str(num))

    def expect_ip_surcharge_title_to_be_visible(self) -> [bool, None]:
        """判断IP附加费弹框是否可见"""
        count = 0
        while count < 5:
            elements = self.page.query_selector_all("//*[@id='modalId']/div[1]/h4")
            log.debug(f"元素数量:{len(elements)},元素:{elements}")
            if len(elements) >= 2:
                second_element = elements[1]
                log.info(f"IP附加费是否可见:{second_element.is_visible()}")
                if second_element.text_content() == "IP附加费":
                    return True
                else:
                    continue
            else:
                log.warning("IP附加费弹框提示框未找到,继续尝试等待...")
            count += 1
            time.sleep(3)
        return False

    @allure.step("获取删除私有网络弹框警告内容")
    def get_release_eip_alert_warning_info(self):
        """获取删除EIP弹框警告内容"""
        alert_text_content = self.popout.get_alert_warning_text_content()
        return alert_text_content

    def check_eipv4_page_user_guide_element_to_be_visible(self):
        """检查ipv4 检查使用指南元素是否可见"""
        with allure.step("检查EIPv4_Page:使用指南元素是否可见"):
            self.expect.to_be_visible(self.page.locator(".intro"))  # 使用指南栏目
            self.expect.to_be_visible(self.page.get_by_text("使用指南"))
            self.expect.to_be_visible(self.page.get_by_role("link", name="公网 IPv4"))
            self.expect.to_be_visible(self.page.get_by_text("收起"))
            self.expect.to_be_visible(self.page.locator(".svg-icon > use"))
            self.expect.to_be_visible(self.page.get_by_text("温馨提示：根据《非经营性互联网信息服务备案管理》要求，"
                                                            "未备案公网 IP 80/443 端口将被禁用，如需使用上述端口，"
                                                            "则公网IP必须提交 ICP 备案信息。"))
            self.expect.to_contain_text(self.page.locator(".tab-intro .text"),
                                        "云平台 为您提供独立的公网 IP 资源，包括公网IP地址及公网出口带宽服务。"
                                        "公网 IPv4 地址与您的账户而非特定的资源关联")

    def check_eipv6_page_user_guide_element_to_be_visible(self):
        """检查ipv6 检查使用指南元素是否可见"""
        with allure.step("检查EIPv6_Page:使用指南元素是否可见"):
            self.expect.to_be_visible(self.page.locator(".intro"))  # 使用指南栏目
            self.expect.to_be_visible(self.page.get_by_text("使用指南"))
            self.expect.to_be_visible(self.page.get_by_role("link", name="公网 IPv6"))
            self.expect.to_be_visible(self.page.get_by_text("收起"))
            self.expect.to_be_visible(self.page.locator(".svg-icon > use"))
            self.expect.to_be_visible(self.page.get_by_text("温馨提示：根据《非经营性互联网信息服务备案管理》要求，"
                                                            "未备案公网 IP 80/443 端口将被禁用，如需使用上述端口，"
                                                            "则公网IP必须提交 ICP 备案信息。"))
            self.expect.to_contain_text(self.page.locator(".tab-intro .text"),
                                        "云平台 为您提供独立的公网 IP 资源，包括公网IP地址及公网出口带宽服务。公网 IPv6 地址有两种")

    def check_eip_page_table_element_to_be_visible(self):
        """检查工具栏及table是否可见"""
        with allure.step("检查EIPv4_Page:工具栏及table是否可见"):
            self.expect.to_be_visible(self.page.locator(".table-toolbar"))
            self.expect.to_be_visible(self.page.get_by_role("link", name="G", exact=True))
            self.expect.to_be_visible(self.page.locator("a").filter(has_text="申请"))
            self.expect.to_be_visible(self.page.get_by_placeholder(" "))
            self.expect.to_be_visible(self.page.get_by_role("combobox"))
